package com.voxel.sense.infomsg.module.login;

import android.text.TextUtils;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.RegexUtils;
import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.UserEntity;
import cyy.example.com.facotry.net.helper.DbHelper;
import cyy.example.com.facotry.net.helper.NetHelper;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by ChenYiYao on 2018/2/1.
 */

public class LoginPresenter extends BasePresenter<LoginContract.View>
        implements LoginContract.Presenter, DataSource.Callback<BaseEntity<UserEntity>> {

    private String mPsw;
    private String mAcount;
    private UserEntity mData;

    @Override
    public void start() {
        super.start();
        LoginContract.View view = getView();
        //进行初始化的一些工作
        view.initPswEditText(SPEngine.getSPEngine().isRememberPsw(), SPEngine.getSPEngine().getUserInfo().getPsw());
        String accout = SPEngine.getSPEngine().getUserInfo().getUser_account();
        if (!TextUtils.isEmpty(accout)) {
            view.setAccount(accout);
        }

        SPEngine.getSPEngine().getUserInfo().setToken("");
        SPEngine.getSPEngine().setLoginState(false);
    }

    public LoginPresenter(LoginContract.View view) {
        super(view);
    }

    @Override
    public void login(String account, String psw) {
        if (NetworkUtils.isConnected()) {
            if (TextUtils.isEmpty(account)) {
                mView.showError("账号不能为空，请输入账号");
            } else if (TextUtils.isEmpty(psw)) {
                mView.showError("密码不能为空，请输入密码");
            } else {
//                mView.showLoading("请稍等", false);
                mPsw = psw;
                mAcount = account;
//                NetHelper.requestLogin(account, psw, this);
                NetHelper.login(account, psw, this);
            }
        } else {
            mView.showError(Factory.app().getResources().getString(R.string.network_unavailable));
        }
    }

    @Override
    public void setRememberPsw(boolean flag) {
        SPEngine.getSPEngine().setRememberPsw(flag);
    }

    @Override
    public void upIdCardNumb(String numb) {
        if (!NetworkUtils.isConnected()) {
            mView.showError(Factory.app().getResources().getString(R.string.network_unavailable));
        } else if (RegexUtils.isIDCard18(numb)) {
            //校验成功，上传身份证
            mView.showLoading("");
            NetHelper.upUserIdCard(mData.getUserId(), numb, new DataSource.Callback<BaseEntity<String>>() {
                @Override
                public void onDataNotAvailable(String strRes, int reqId) {
                    if (mView == null) {
                        return;
                    }

                    mView.dimissLoading();
                    mView.onDismissIdcardDialog();
                    mView.showError(Factory.app().getResources().getString(R.string.network_request_error));
                }

                @Override
                public void onDataLoaded(BaseEntity<String> data, int reqId) {
                    if (mView == null) {
                        return;
                    }

                    mView.dimissLoading();
                    mView.onDismissIdcardDialog();
                    if (data.isSuccess() && "1".equals(data.getData())) {
                        LoginSuccess(mData);
                    } else {
                        mView.showError("身份验证失败");
                    }
                }
            });
        } else {
            mView.showError("请填入正确的身份证号码");
        }
    }

    @Override
    public void onDataLoaded(BaseEntity<UserEntity> userEntity, int reqId) {
        if (mView == null) {
            return;
        }

        mView.dimissLoading();
        //登录成功
        if (userEntity != null && userEntity.isSuccess() && userEntity.getData() != null) {
            mData = userEntity.getData();
            if ("1".equals(mData.getIdCardExist())) {
                //用户需要上传身份证
                mView.onShowIdCardDialog();
            } else {
                LoginSuccess(mData);
            }
        } else {
            mView.showError(userEntity.getMessage());
        }
    }

    private void LoginSuccess(UserEntity data) {
        SPEngine.UserInfo userInfo = SPEngine.getSPEngine().getUserInfo();

        userInfo.setEmail(data.getEmail());
        userInfo.setPhone(data.getPhone());
        userInfo.setPortrait(data.getHeadPhotoAddr());
        userInfo.setName(data.getRealname());
        userInfo.setRoleId(data.getRoleId());
        userInfo.setRoleName(data.getRoleName());
        userInfo.setToken(data.getToken());
        userInfo.setSetMobileToken(data.getMobileToken());
        userInfo.setUserDetailId(data.getUserDetailId());
        userInfo.setUser_id(data.getUserId());
        userInfo.setRegionCode(data.getRegionCode());
        userInfo.setDistributing(data.getDistributing());
        userInfo.setUser_account(mAcount);
        userInfo.setPsw(mPsw);
        SPEngine.getSPEngine().setLoginState(true);
        SPEngine.getSPEngine().setmRoleId(data.getRoleId());

        DbHelper.getInstance().initDB();//先关闭清除一次
        //加载搜索配置文件
        QueryConfigManager.getInstance().getSearchMenuconfig(true);
        QueryConfigManager.getInstance().getAppConfig(true);
        //初始化推送别名
        App.getInstance().setPushAlias();
        mView.loginSuccess();
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }
        mView.dimissLoading();
        mView.loginFailure(strRes);
        mView.showError(Factory.app().getString(R.string.network_error));
    }
}
